package com.iap.client.view.client.code
{
	import com.iap.admin.view.code.EditViewCode;
	import com.iap.app.util.FormUtils;
	import com.iap.client.view.client.ClientEditWindow;
	import com.iap.common.model.ClientLite;
	import com.iap.common.signal.ClientLiteRequestSignal;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Alert;
	import mx.managers.PopUpManager;
	
	public class ClientEditWindowCode extends EditViewCode
	{
		public static const CANCEL_NAME:String = "ClientEdit.Cancel";
		public static const SAVE_NAME:String = "ClientEdit.Save";
		public static const DELETE_NAME:String = "ClientEdit.Delete";
		
		public var onSubmit:ClientLiteRequestSignal = new ClientLiteRequestSignal();
		
		private var view:ClientEditWindow;
		public var canCloseForm:Boolean = false;
		
		public function ClientEditWindowCode()
		{
			super();
		}
		
		protected function initView(view:ClientEditWindow):void
		{
			this.view = view;
			addListener();
			initValidators();
			resetFocus();
			onReady.dispatch("ready");
		}
		
		private function initValidators():void
		{
		}
		
		private function addListener():void
		{
			view.nameForm.addEventListener(Event.CHANGE, validateForm);
		}
		
		private function removeListener():void
		{
			view.nameForm.removeEventListener(Event.CHANGE, validateForm);
		}
		
		private function resetFocus():void
		{
		}
		
		private function save(evt:Event = null):void
		{
			if(formIsValid)
				submit();
		}
		
		protected function submit(closeForm:Boolean = false):void 
		{
			canCloseForm = closeForm;
			model ||= new ClientLite();
			model = FormUtils.fillObjectFromControls(view, model, FORM_PREFIX);
			onSubmit.dispatch(model, ClientLiteRequestSignal.SAVE);
		}
		
		protected function remove():void 
		{
			var clientLite:ClientLite = model as ClientLite;
			if(clientLite.instanceLites.length > 0)
			{
				Alert.show("Primero debe borrar todas las instancias.");
				return;
			}
			onSubmit.dispatch(model, ClientLiteRequestSignal.DELETE);
		}
		
		override public function fill(model:Object):void
		{
			super.fill(model);
		}
		
		protected function cancelClickHandler(evt:MouseEvent):void
		{
			closeView();
		}
		
		public function closeView():void
		{
			PopUpManager.removePopUp(this);
		}
	}
}